package com.letchat.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.letchat.mapper.CommentMapper;
import com.letchat.mapper.SubjectMapper;
import com.letchat.mapper.UserMapper;
import com.letchat.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SubjectService {
    @Autowired
    private SubjectMapper scubjectMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取主题详情
     * @param id
     * @return
     */

    public Subject getSubjectDetailById(Integer id) {
        Subject subject = scubjectMapper.getSubjectById(id);
        subject.setUser(userMapper.getIdAndNameAndImgById(subject.getUserId()));
        subject.setCommentParentList(commentMapper.getCommentParentListBySubjectId(id));
        for (CommentParent commentParent : subject.getCommentParentList()){
            commentParent.setUser(userMapper.getIdAndNameAndImgById(commentParent.getUserId()));
            commentParent.setCommentChildList(commentMapper.getCommentChildListByParentId(commentParent.getId()));
            for (CommentChild commentChild : commentParent.getCommentChildList()){
                commentChild.setUser(userMapper.getIdAndNameAndImgById(commentChild.getUserId()));
            }
        }
        return subject;
    }

    /**
     * 主题列表
     * @param page
     * @param pageSize
     * @param subject
     * @return
     */
    public PageBean sujectList(Integer page, Integer pageSize,String subject){
        PageHelper.startPage(page, pageSize);
        List<Subject> subjectList = scubjectMapper.subjectList(subject);
        for (Subject s : subjectList){
            s.setUser(userMapper.getIdAndNameAndImgById(s.getUserId()));
        }
        Page<Subject> p = (Page<Subject>) subjectList;
        return new PageBean(p.getTotal(), p.getResult());
    }

    /**
     * 删除主题
     * @param id
     */
    @Transactional
    public void deleteSubject(Integer id) {
        List<CommentParent> commentParentList = commentMapper.getCommentParentListBySubjectId(id);
        for (CommentParent commentParent : commentParentList){
            commentMapper.deleteCommentChildByParentId(commentParent.getId());
        }
        commentMapper.deleteCommentParentBySubjectId(id);
        scubjectMapper.deleteSubjectById(id);
    }

}
